package com.yyj.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yyj.domain.Car;
import com.yyj.domain.User;
import com.yyj.service.CarService;

@Controller
public class CarController {
	@Autowired
	private CarService carService;

	@RequestMapping("/insertgwc.do")
	public String insertgwc(Car car) {
		carService.insertcar(car);
		return "redirect:home.do";
	}

	@RequestMapping(value = "/getAllCarts.do")
	public String getAllGoods(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<Car> carts = carService.getAllCarts(user.getAccount());
		System.out.println(carts);
		model.addAttribute("carts", carts);
		return "gwc";
	}

	@RequestMapping(value = "/goodsInfo.do")
	public String getGoodsByGoodsid(Integer goods_id, Model model) {
		Car carts = carService.getCarts(goods_id);
		model.addAttribute("carts", carts);
		return "goodsInfo";
	}


	@RequestMapping("/updateCartsMinus.do")
	@ResponseBody
	public Car updateCartsMinus(@RequestBody Car carts) {
		Car cartss = carService.getCarts(carts.getGoods_id());
		cartss.setSum(carts.getNumber() * cartss.getPrice());
		cartss.setNumber(carts.getNumber());
		int n = carService.updateCarts(cartss);
		if (n > 0) {
			System.out.println(cartss);
		}
		return cartss;
	}

	
	@RequestMapping("/updateCartsAdd.do")
	@ResponseBody
	public Car updateCartsAdd(@RequestBody Car carts) {
		Car cartss = carService.getCarts(carts.getGoods_id());
		cartss.setSum(carts.getNumber() * cartss.getPrice());
		cartss.setNumber(carts.getNumber());
		int n = carService.updateCarts(cartss);
		if (n > 0) {
			System.out.println(cartss);
		}
		return cartss;
	}

	
	@RequestMapping("/deleteCarts.do")
	@ResponseBody
	public ModelAndView deleteCarts(Integer goods_id, HttpSession session) {
		int rows = carService.deleteCarts(goods_id);
		ModelAndView mav = new ModelAndView("gwc");
		User user = (User) session.getAttribute("user");
		List<Car> carts = carService.getAllCarts(user.getAccount());
		mav.addObject("carts", carts);
		return mav;
	}

}
